/*
 * CheatWipe.java
 *
 * Created on January 1, 2010, 12:47 PM
 */

package torchtools.gui;

import java.awt.event.ActionEvent;
import java.io.File;
import java.io.IOException;
import java.text.MessageFormat;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import torchtools.binary.TLPlayerSave;
import torchtools.binary.TLSave;

/**
 *
 * @author  Matt
 */
public class CheatWipe extends BaseTool {
    
    private static final String LEVEL_MSG = "Level {0} {1}";
    public static final String CHEAT_SUFFIX = " the cheat";
   
    /** Creates new form CheatWipe */
    public CheatWipe() {
        //init CheatWipe's GUI components
        initComponents();
        
        //since the "Remoev Cheat Flag" button will save the file, we don't
        //need a File > Save menu item
        fileMenu.remove(saveMenuItem);
        
        //I'm also getting rid of the Help option since it's already explained
        //in the tool itself.
        helpMenu.remove(helpMenuItem);
        
        pack();
        setLocationRelativeTo(null);
        
        //have the fields cleared on open
        clear();
    }
    
    //called on Help > About
    protected void aboutAction(ActionEvent e) {
        String msg = "<html>Cheat Flag Remover -- created by mattdesl.</html>";
        JOptionPane.showMessageDialog(this, msg, "About", JOptionPane.PLAIN_MESSAGE);
    }
    
    //called to create the TLPlayerSave on File > Open
    protected TLPlayerSave createPlayerSave(File path) throws IOException {
        TLPlayerSave save = new TLPlayerSave(path, "rw", false);
        save.readPlayerInfo();
        return save;
    }
    
    //closes the file and clear the fields
    protected void clear() {
        super.clear();
        nameLabel.setText("No Save Specified");
        levelLabel.setText("");
        removeCheatBtn.setEnabled(false);
    }
    
    //called to save properties to the file
    protected boolean saveFileImpl() throws IOException {
        boolean success = true;
        
        //get old name
        String oldName = save.getPlayerName();
        //if cheater, reset the flag
        //best to do this first, since replacing strings may close() the file
        if (save.isCheater())
            save.writeCheater(false);
        
        //if ends with " the Cheat", remove it
        if (oldName.toLowerCase().endsWith(CHEAT_SUFFIX)) {
            //the new name without " the Cheat"
            String newName = oldName.substring(0, oldName.length()-CHEAT_SUFFIX.length());
            
            //seek to the player name pointer and replace it with the new string
            save.seek(save.getPlayerNamePtr());
            int r = TLSave.replaceTLString(save, newName);
            
            //update the text
            nameLabel.setText(newName);
            
            //-1 means unsuccessful 
            success = r!=-1;
        }
        //since it's been removed, we can disable the button
        removeCheatBtn.setEnabled(false);
        return success;
    }
    
    protected void openFile(File path) throws IOException {
        //don't forget to call this -- it will load the save file!
        super.openFile(path);
        //now we can use TLPlayerSave to update our GUI components
        nameLabel.setText(save.getPlayerName());
        levelLabel.setText(MessageFormat.format(LEVEL_MSG, save.getLevel(), save.getPlayerClass()));
        removeCheatBtn.setEnabled(save.isCheater());
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        nameLabel = new javax.swing.JLabel();
        removeCheatBtn = new javax.swing.JButton();
        levelLabel = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        guide = new javax.swing.JEditorPane();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Cheat Wipe");

        nameLabel.setFont(nameLabel.getFont().deriveFont(nameLabel.getFont().getStyle() | java.awt.Font.BOLD, nameLabel.getFont().getSize()+2));
        nameLabel.setText("<html>Vera The Cheat");

        removeCheatBtn.setText("Remove Cheat Flag");
        removeCheatBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                removeCheatBtnActionPerformed(evt);
            }
        });

        levelLabel.setFont(levelLabel.getFont().deriveFont(levelLabel.getFont().getSize()-1f));
        levelLabel.setText("Level 2 Alchemist");

        jScrollPane1.setBackground(null);
        jScrollPane1.setBorder(null);

        guide.setContentType("text/html");
        guide.setEditable(false);
        guide.setText("<html><font style=\"font-family: Tahoma,Verdana,SansSerif; font-size: 11pt;\">To recover your Shared Stash:<br>\n<ol style=\"margin-left: 25px;\"><li>Use <b>File > Open</b> to select your save file in Cheat Wipe, then click the <b>Remove Cheat Flag</b> button. Quit Cheat Wipe.</li>\n<li>Run Torchlight and open your character. Spawn a shared stash in town with the console. This will flag you as a cheater again.</li>\n<li>Close Torchlight and open Cheat Wipe. Open your save file again. Click the <b>Remove Cheat Flag</b> button to remove the cheat flag.</li>\n</ol></font></html>");
        guide.setOpaque(false);
        jScrollPane1.setViewportView(guide);

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 246, Short.MAX_VALUE)
                    .add(removeCheatBtn, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 246, Short.MAX_VALUE)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, levelLabel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 246, Short.MAX_VALUE)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, nameLabel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 246, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(nameLabel)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(levelLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 14, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 217, Short.MAX_VALUE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(removeCheatBtn)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void removeCheatBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeCheatBtnActionPerformed
        this.saveFileAction(evt);
    }//GEN-LAST:event_removeCheatBtnActionPerformed
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); }
        catch (Exception e) {}
        
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new CheatWipe().setVisible(true);
            }
        });
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JEditorPane guide;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel levelLabel;
    private javax.swing.JLabel nameLabel;
    private javax.swing.JButton removeCheatBtn;
    // End of variables declaration//GEN-END:variables

}
